const { Router } = require("express")
const md5 = require("md5")
const JWT = require("jsonwebtoken")
const User = require("../model/User")
const { v4: uuidv4 } = require("uuid")
const router = new Router()



// 注册接口 http://localhost:8000/api/user/register
router.post("/register", async (req, res) => {
  const { phone, password, gender, identitycard, hobboy, hometown, industry } =
    req.body;
  console.log(
    phone,
    password,
    gender,
    identitycard,
    hobboy,
    hometown,
    industry
  );

  if (!password || !phone) {
    res.ststus(400).json({ message: "密码和手机号必填" });
    return;
  }
  //用户是否存在
  const user = await User.findOne({ phone });
  if (user) {
    res.status(400).json({ message: "该用户已存在" });
    return;
  }
  //注册user
  await User.create({
    phone,
    password: md5(password),
    gender,
    identitycard,
    hobboy,
    hometown,
    industry,
  });
  res.status(200).json({ message: "注册成功" });
});

// 登录的接口 http://localhost:8000/api/user/login
router.post("/login", async (req, res) => {
  const { phone, password } = req.body;
  console.log(phone, password);

  if (!phone || !password) {
    res.status(400).json({ message: "缺少参数" });
    return;
  }
  const user = await User.findOne(
    { phone, password: md5(password) },
    {
      password: false,
    }
  ).lean();
  if (user) {
    const token = JWT.sign(user, "hello world", { expiresIn: "15d" });
    res.status(200).json({ message: "登录成功", token });
  } else {
    res.status(400).json({ message: "手机号或密码错误" });
  }
});


// 手机号是否存在
router.post("/testphone", async (req, res) => {
  let { phone } = req.body
  // console.log(phone);
  const phones = await User.findOne({ phone });
  if (!phones) {
    res.status(400).json({ message: "该手机号码不存在" });
    return;
  }
  res.status(200).json({ message: 'ok' })
  // res.send('222')
})


// 修改密码
router.post("/updatepsw", async (req, res) => {
  let { phone, password } = req.body;
  // console.log(phone,password);
  const modifyphone = await User.findOneAndUpdate(
    { phone },
    { password: md5(password) }
  );
  // console.log(modifyphone);
  if (!modifyphone) {
    res.status(400).json({ message: '修改失败' })
    return
  }
  res.status(200).json({ message: "修改成功" });
})


/* 
检查用户是否登录了
url: /api/user/check_login
method: GET
header: authorization
*/
router.use(require('../middleware/auth.js'));

router.get("/check_login", async (req, res) => {
  res.status(200).json({ message: "登录成功", data: req.userInfo });
});



module.exports = router;
